package com.longteng.diamond.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.longteng.diamond.constant.BuildTestStatus;
import com.longteng.diamond.domain.*;
import com.longteng.diamond.po.RequestResult;
import com.longteng.diamond.po.TablePage;
import com.longteng.diamond.po.TreeMenu;
import com.longteng.diamond.service.BuildTestService;
import com.longteng.diamond.service.TestPlanService;
import com.longteng.diamond.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator
 * DATE : 2018/7/6
 * TIME : 20:20
 * PROJECT : java-lesson
 * PACKAGE : com.longteng.lesson
 *
 * @author <a href="mailto:taki@qq.com">Administrator</a>
 */
@Controller
@Slf4j
@RequestMapping("/testPlanController")
public class TestPlanController {
    @Autowired
    TestPlanService testPlanService;
    @Autowired
    BuildTestService buildTestService;

    @RequestMapping("/planPage")
    public ModelAndView testPlanPage(Integer buildTestId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("buildTestId", buildTestId);
        Integer projectId = SessionUtil.getSessionUser().getLastProjectId();
        /**
         * 获取运行中的构建记录
         */
        BuildTest buildTest = buildTestService.getBuildTestRunning(projectId);
        modelAndView.addObject("runningBuildTest", buildTest);
        /**
         * 获取左侧测试计划树
         */
        List<TreeMenu> testPlanTree = testPlanService.getTestPlanTree(projectId);
        if (!CollectionUtils.isEmpty(testPlanTree)) {
            modelAndView.addObject("planTreeJson", JSON.toJSONString(testPlanTree));
        }
        /**
         * 获取最后一个新增的测试计划
         * */
        TestPlan lastTestPlan = testPlanService.getLastPlan(projectId);
        modelAndView.addObject("lastTestPlan", lastTestPlan);
        /**
         * 获取右侧运行记录列表
         */
        List<BuildTest> buildTestList = buildTestService.getBuildTestByProjectId(projectId);
        modelAndView.addObject("buildTestList", buildTestList);
        /**
         * 如果当前项目没有创建过测试计划,并且也没有正在执行的计划,获取最后的测试计划
         * **/
        if(null ==lastTestPlan && null==buildTest && !CollectionUtils.isEmpty(buildTestList)){
            modelAndView.addObject("runningBuildTest", buildTestList.get(buildTestList.size()-1));
        }
        modelAndView.setViewName("page/testplan/testPlanPage");
        return modelAndView;
    }

    /**
     * 获取构建列表
     *
     * @param projectId
     * @return List<BuildTest>
     */
    @RequestMapping("/getBuildTestByProjectId")
    public @ResponseBody
    List<BuildTest> getBuildTestByProjectId(Integer projectId) {
        return buildTestService.getBuildTestByProjectId(projectId);
    }

    ;

    @RequestMapping("/planList")
    public @ResponseBody
    Map p() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<TestPlan> list = Lists.newArrayList();
        TestPlan testPlan = new TestPlan();
        testPlan.setTestPlanName("测试计划");
        list.add(testPlan);
        map.put("plan", 1);
        map.put("pageNumber", 10);
        map.put("list", list);
        return map;
    }

    /**
     * 获取构建记录
     *
     * @param buildTestId
     * @return BuildTest
     */
    @RequestMapping("/getBuildTest")
    public @ResponseBody
    RequestResult getBuildTest(Integer buildTestId) {
        RequestResult requestResult = new RequestResult();
        try {
            BuildTest buildTest = buildTestService.buildRunTest(buildTestId);
            requestResult.setObj(buildTest);
            requestResult.setSuccess(true);
        } catch (Exception e) {
            requestResult.setSuccess(false);
            requestResult.setMsg("获取构建记录错误,请联系管理员!");
            log.error("获取构建记录异常", e);
        }
        return requestResult;
    }

    /**
     * 读取运行日志
     *
     * @param buildTestId
     * @param lastTimeFileSize
     * @return ReportLog
     */
    @RequestMapping("/runLog")
    public @ResponseBody
    ReportLog runLog(Integer buildTestId, Long lastTimeFileSize) {
        return testPlanService.runLog(buildTestId, lastTimeFileSize);
    }

    /**
     * 获取测试计划树
     *
     * @param projectId
     * @return requestResult
     */
    @RequestMapping("/getPlanTree")
    public @ResponseBody
    RequestResult getPlanTree(Integer projectId) {
        RequestResult requestResult = new RequestResult();
        try {
            List<TreeMenu> treeList = testPlanService.getTestPlanTree(projectId);
            requestResult.setObj(treeList);
            requestResult.setSuccess(true);
        } catch (Exception e) {
            log.error("获取测试计划错误", e);
            requestResult.setSuccess(false);
            requestResult.setMsg("获取测试计划异常,请联系管理员!");
        }
        return requestResult;
    }

    /**
     * 获取测试计划
     *
     * @param testPlanId
     * @return requestResult
     */
    @RequestMapping("/getTestPlanById")
    public @ResponseBody
    RequestResult getTestPlanById(Integer testPlanId) {
        RequestResult requestResult = new RequestResult();
        try {
            TestPlan testPlan = testPlanService.getTestPlanById(testPlanId);
            requestResult.setObj(testPlan);
            requestResult.setSuccess(true);
        } catch (Exception e) {
            log.error("获取测试计划错误", e);
            requestResult.setSuccess(false);
            requestResult.setMsg("获取测试计划异常,请联系管理员!");
        }
        return requestResult;
    }

    /**
     * 新增测试计划
     *
     * @param testPlan
     * @param testCaseIds
     * @return
     */
    @RequestMapping("/addTestPlan")
    public @ResponseBody
    RequestResult addTestPlan(@Valid TestPlan testPlan, BindingResult bindingResult, Integer[] testCaseIds) {
        RequestResult requestResult = new RequestResult();
        if (bindingResult.hasErrors()) {
            requestResult.setMsg(bindingResult.getFieldError().getDefaultMessage());
            requestResult.setSuccess(false);
            return requestResult;
        }
        if (null == testCaseIds || testCaseIds.length == 0) {
            requestResult.setMsg("请选择测试用例在保存计划");
            requestResult.setSuccess(false);
            return requestResult;
        }
        try {
            String userName = SessionUtil.getSessionUser().getUserName();
            testPlan.setRunUser(userName);
            Integer testPlanId = testPlan.getTestPlanId();
            if (null == testPlanId) {
                testPlanService.addTestPlan(testPlan, testCaseIds);
            } else {
                testPlanService.updateTestPlan(testPlan, testCaseIds);
            }
            requestResult.setSuccess(true);
        } catch (Exception e) {
            log.error("增加测试计划异常", e);
            requestResult.setSuccess(false);
            requestResult.setMsg("增加测试计划异常,请联系管理员");
        }
        return requestResult;
    }

    /**
     * 删除测试计划
     *
     * @param testPlanId
     * @return
     */
    @RequestMapping("/deleteTestPlan")
    public ModelAndView deleteTestPlan(Integer testPlanId) {
        ModelAndView modelAndView = new ModelAndView();
        testPlanService.deleteTestPlan(testPlanId);
        modelAndView.setViewName("redirect:/testPlanController/plan");
        return modelAndView;
    }

    /**
     * 运行测试计划
     *
     * @param testPlanName
     * @param testPlanId
     * @return list
     */
    @RequestMapping("/buildPlan")
    @ResponseBody
    public RequestResult buildPlan(Integer testPlanId, String testPlanName, Integer projectId) {
        RequestResult requestResult = new RequestResult();
        try {
            String userName = SessionUtil.getSessionUser().getUserName();
            BuildTest buildTest = new BuildTest();
            buildTest.setTestPlanName(testPlanName.trim());
            buildTest.setProjectId(projectId);
            buildTest.setUserName(userName);
            buildTest.setStatus(BuildTestStatus.running);
            buildTest.setTestPlanId(testPlanId);
            Integer buildTestId = buildTestService.buildTestPlan(buildTest);
            requestResult.setSuccess(true);
            requestResult.setObj(buildTestId);
        } catch (Exception e) {
            log.error("增加构建任务异常", e);
            requestResult.setSuccess(false);
            requestResult.setMsg("构建任务异常,请联系管理员!");
        }
        return requestResult;
    }

    /**
     * 批量运行多个接口
     *
     * @param buildTest
     * @param interfaceIds
     * @return list
     */
    @RequestMapping("/buildTempPlan")
    @ResponseBody
    public RequestResult buildTempPlan(BuildTest buildTest, Integer[] interfaceIds) {
        RequestResult requestResult = new RequestResult();
        try {
            String userName = SessionUtil.getSessionUser().getUserName();
            buildTest.setUserName(userName);
            buildTest.setStatus(BuildTestStatus.running);
            Integer buildTestId = buildTestService.saveBuildTest(buildTest, interfaceIds);
            requestResult.setSuccess(true);
            requestResult.setObj(buildTestId);
        } catch (Exception e) {
            log.error("增加构建任务异常", e);
            requestResult.setSuccess(false);
            requestResult.setMsg("构建任务异常,请联系管理员!");
        }
        return requestResult;
    }

    /**
     * 批量运行多个测试用例
     *
     * @param buildTest
     * @param caseIds
     * @return requestResult
     */
    @RequestMapping("/buildTempPlanTestCase")
    public @ResponseBody
    RequestResult buildTempPlanTestCase(BuildTest buildTest, Integer[] caseIds) {
        RequestResult requestResult = new RequestResult();
        try {
            String userName = SessionUtil.getSessionUser().getUserName();
            buildTest.setUserName(userName);
            buildTest.setStatus(BuildTestStatus.running);
            Integer buildTestId = buildTestService.saveBuildTestCase(buildTest, caseIds);
            requestResult.setSuccess(true);
            requestResult.setObj(buildTestId);
        } catch (Exception e) {
            requestResult.setSuccess(false);
            requestResult.setMsg("构建测试计划异常,请联系管理员!");
            log.error("构建测试计划异常!", e);
            return requestResult;
        }
        return requestResult;
    }

    /**
     * 获取所有构建测试用例
     *
     * @param buildTestCase
     * @return tablePage
     */
    @RequestMapping("/getTestCase")
    public @ResponseBody
    TablePage getTestCase(BuildTestCase buildTestCase) {
        TablePage tablePage = new TablePage();
        try {
            tablePage = buildTestService.getTestCase(buildTestCase);
        } catch (Exception e) {
            log.error("获取用户错误:", e);
        }
        return tablePage;
    }

    /**
     * 获取所有构建测试用例
     *
     * @param buildTestId
     * @param interfaceId
     * @return tablePage
     */
    @RequestMapping("/buildTestCasePage")
    public ModelAndView buildTestCasePage(Integer buildTestId, Integer interfaceId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("buildTestId", buildTestId);
        modelAndView.addObject("interfaceId", interfaceId);
        modelAndView.setViewName("page/buildInterface/buildTestCasePage");
        return modelAndView;
    }
}
